<?php

namespace app\api\model;

use think\Model;

/**
 * Notice
 */
class Notice extends Model
{
    // 表名
    protected $name = 'notice';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    protected static function onAfterInsert($model): void
    {
        if ($model->weigh == 0) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }

    public function getContentAttr($value): string
    {
        return !$value ? '' : htmlspecialchars_decode($value);
    }


    public function getNotice($params){
        $member_id = $params['member_id'] ?? 0;
        $readLog = [];
        if($member_id){
           $readLog = (new NoticeLog())->where(['member_id' => $member_id])->column('notice_id');
        }
        $map[] = ['status','=',1];
        $list = self::field('id,name,content,create_time')->where($map)->order('weigh desc')->paginate(10);
        foreach($list as &$val){
           $val['is_read'] = in_array($val['id'],$readLog) ? 1 : 2;
           $val['create_time'] = date("Y/m/d H:i:s",$val['create_time']);
        }
        return api_message($list);
    }


    public function readNotice($params){
        $id = $params['notice_id'] ?? 0;
        $member_id = $params['member_id'] ?? '';
        $result = self::where(['id' => $id,])->find();
        if(!$result || !$member_id){
            return api_message();
        }
        //更新状态
        $model = new NoticeLog();
        $noticeLog = $model->where(['notice_id' => $id,'member_id' => $member_id])->find();
        if($noticeLog){
            return api_message();
        }
        $model->member_id = $member_id;
        $model->notice_id = $id;
        $model->is_read = 1;
        $model->read_time = time();
        $model->save();

        return api_message();

    }
}